package zwp.exercise.service.exercisedemo.chapterThree.basicdatatypes;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

public class BMIexponentAnswer {

    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
    private static final AtomicLong lastActivityTime = new AtomicLong(System.currentTimeMillis());
    private static final long IDLE_TIMEOUT_MS = 10000;

    private static final double THIN_CONSTANT = 18.5d;
    private static final double COMMON_CONSTANT = 24.9d;
    private static final double FAT_CONSTANT = 29.9d;
    private static final String YES = "Y";
    private static final String NO = "N";

    static int countNum = 0;
    static List<String> validInputs = Arrays.asList(YES, NO);

    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {
            AtomicReference<String> isYes = new AtomicReference<>();
            // 启动空闲检测
            startIdleDetection();

            do {
                // 计算BMI
                evaluateBMI(scanner);

                // 询问是否继续
                System.out.println("是否需要更改数据，再次查看您的BMI指数? 请输入：Y/N");
                isYes.set(getUserInput(scanner));

                // 用户操作后重置倒计时
                onUserActivity();

            } while (YES.equalsIgnoreCase(isYes.get()));

        } finally {
            scheduler.shutdown();
        }
    }

    private static String getUserInput(Scanner scanner) {
        while (true) {
            String input = scanner.next().toUpperCase();
            if (validInputs.contains(input)) {
                return input;
            }
            System.out.println("输入错误，请重新输入：Y/N");
        }
    }

    private static void onUserActivity() {
        lastActivityTime.set(System.currentTimeMillis());
        System.out.println("检测到用户操作，重置计时器");
    }

    private static void startIdleDetection() {
        scheduler.scheduleAtFixedRate(() -> {
            long idleTime = System.currentTimeMillis() - lastActivityTime.get();
            if (idleTime >= IDLE_TIMEOUT_MS) {
                System.out.println(IDLE_TIMEOUT_MS/1000 + "秒无操作，系统自动关闭！");
                scheduler.shutdown();
                // 用于强制终止当前正在运行的 Java 虚拟机（JVM）的方法。
                // 它的作用是立即停止程序运行，并返回一个状态码给操作系统。
                // 原因：使用了后台线程（ScheduledExecutorService）来检测空闲时间，即使主线程结束，后台线程仍可能继续运行，导致 JVM 不会自动退出。
                System.exit(0);
            }
        }, 1, 1, TimeUnit.SECONDS);
    }

    private static void evaluateBMI(Scanner scanner) {
        onUserActivity();

        System.out.println("请输入您的身高(cm)：");
        double height = scanner.nextDouble() / 100;

        System.out.println("请输入您的体重(kg)：");
        int weight = scanner.nextInt();

        onUserActivity();

        double exponent = weight / (height * height);
        System.out.println("您的身高为：" + height * 100 + "cm");
        System.out.println("您的体重为：" + weight + "kg");
        System.out.println("您的BMI指数为：" + exponent);

        String finalEvaluation;
        if (exponent < THIN_CONSTANT) {
            finalEvaluation = "体重过轻";
            countNum = 0;
        } else if (exponent < COMMON_CONSTANT) {
            finalEvaluation = "正常范围";
            countNum = 1;
        } else if (exponent < FAT_CONSTANT) {
            finalEvaluation = "体重过重";
            countNum = 2;
        } else {
            finalEvaluation = "肥胖";
            countNum = 3;
        }
        System.out.println("您的体重属于：" + finalEvaluation);

        switch (countNum) {
            case 1:
                System.out.println("继续保持哦！");
                break;
            case 2:
                System.out.println("平时需要少吃点油炸食品了哦！");
                break;
            case 3:
                System.out.println("为了您的健康，您不能再胖了，请不要再过度饮食！");
                break;
            default:
                System.out.println("为了您的健康，请吃点好的！增加下体重！");
        }
    }
}